<template>
  <div class="box">
    <!-- <el-card>
    <el-row :gutter="20">
      <el-col :span="24">
      </el-col>
    </el-row>
    </el-card>-->
    <el-card style="width: 100%; over-flow: scroll">
      <div slot="header" class="clearfix">
        <span>图片管理</span>
      </div>
      <div style="margin-bottom: 20px">
        <el-button type="primary" @click="formShow()">新增</el-button>
      </div>
      <!-- <div style="width: 384px; margin-right: 5px; margin-top: 10px">
        <div class="btnUpload" @click="formShow()">
          <img class="uploadImg" src="./upload.png" alt="" srcset="" />
        </div>
      </div> -->
      <div class="listBox">
        <el-table border :data="list" style="width: 100%">
          <el-table-column fixed type="index" />
          <el-table-column prop="name" label="名称" width="180" />
          <el-table-column prop="linkUrl" label="超链接地址" width="300" />
          <el-table-column label="图片类型" width="100" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.type == 2 ? '轮播图' : '中图' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="图片" width="400" align="center">
            <template slot-scope="scope">
              <img
                style="width: 200px"
                :src="scope.row.newurl"
                alt=""
                srcset=""
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" align="center">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="handleClick(scope.row)"
                >编辑</el-button
              >
              <el-button
                type="text"
                style="color: red"
                size="small"
                @click="delClick(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- <el-card
          v-for="(item, index) in list"
          :key="index"
          style="margin-right: 5px; margin-top: 10px"
          @mouseenter="mouseenter(item)"
          @mouseleave="mouseleave"
        >
          <div class="mycard">
            <img
              style="width: 100%; height: 100%"
              :src="item.newurl"
              alt=""
              srcset=""
            />
            <div class="delBox" @click="delClick(item)">
              <img class="delImg" src="./del.png" alt="" srcset="" />
            </div>
          </div>
        </el-card> -->
      </div>
    </el-card>
    <el-dialog
      :title="contentAddForm.id ? '编辑' : '新增'"
      :visible.sync="dialogFormVisible"
    >
      <el-form :rules="rules" label-width="120px" :model="contentAddForm">
        <el-form-item label="图片名称">
          <el-input v-model="contentAddForm.name" />
        </el-form-item>
        <el-form-item label="超链接地址">
          <el-input v-model="contentAddForm.linkUrl" />
        </el-form-item>
        <el-form-item label="图片类型" prop="type">
          <el-select
            v-model="contentAddForm.type"
            placeholder="请选择图片类型"
            :disabled="contentAddForm.id"
          >
            <el-option label="轮播图" :value="2" />
            <el-option label="中图" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="">
          <el-tag v-if="contentAddForm.type == 2" type="danger">
            上传图片长宽需为540*340!
          </el-tag>
          <el-tag v-if="contentAddForm.type == 3" type="danger">
            上传图片长宽需为1200*200!
          </el-tag>
        </el-form-item>

        <el-form-item v-if="contentAddForm.type">
          <el-upload
            class="imgBox"
            :limit="1"
            action="https://jsonplaceholder.typicode.com/posts/"
            :file-list="fileList"
            :before-upload="beforePicUpload"
            list-type="picture-card"
            :http-request="handleUploadImg"
            :on-remove="handleRemove"
          >
            <i class="el-icon-plus" />
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button @click="cancelClick('contentAddForm')">取 消</el-button>
          <el-button type="primary" @click="submitForm('contentAddForm')"
            >确 定</el-button
          >
        </el-form-item>
      </el-form>

      <!-- <div style="color: red">
        <p>上传图片只能是jpg或者png格式!</p>
        <p>上传图片大小不能超过2MB!</p>
        <p>上传图片长宽需为1920*500！!</p>
      </div> -->
    </el-dialog>
  </div>
</template>
<script>
import Oss from '@/utils/oss'
import { addWebImage, updateWebImage, listWebImage } from './api/index'

export default {
  data() {
    return {
      showCode: false,
      fileList: [],
      oss: {},
      dialogFormVisible: false,
      list: [],
      contentAddForm: {
        name: '',
        linkUrl: '',
        url: '',
        type: ''
      },
      imgurl: '',
      loading: true,
      stsToken: {
        accessKeyId: 'LTAI5tCQiELrNuXxFdf5wyuB',
        accessKeySecret: 'VlsN1KXHj4RV709wAOIHOnzjn9Qbke',
        bucket: 'utopia9527',
        region: 'oss-cn-shanghai'
      },
      mouseId: '',
      // ruleForm: {
      //   name: '',
      //   linkUrl: '',
      //   url: '',
      //   type: 2
      // },
      rules: {}
    }
  },
  created() {
    this.oss = new Oss(this.stsToken, window)
    this.oss.__init__()
    setTimeout(() => {
      this.getList()
    }, 2000)
  },
  methods: {
    mouseenter(item) {
      this.mouseId = item.id
    },
    mouseleave() {
      this.mouseId = ''
    },
    cancelClick() {
      this.fileList = []
      this.imgurl = ''
      this.dialogFormVisible = false
    },
    handleClick(item) {
      this.dialogFormVisible = true
      this.imgurl = item.newurl
      this.contentAddForm = Object.assign({}, item, {})
      console.log(item)
      this.fileList = [{ url: item.newurl }]
    },
    formShow() {
      this.fileList = []
      this.imgurl = ''
      this.contentAddForm = {
        type: ''
      }
      this.dialogFormVisible = true
    },
    delClick(item) {
      // this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // })
      this.$alert(
        `<div> <img style="width:192px;height:50px;" src="${item.newurl}"></img></div>`,
        '确认删除此照片',
        {
          dangerouslyUseHTMLString: true
        }
      )
        .then(() => {
          updateWebImage({
            id: item.id,
            state: 2
          }).then((res) => {
            if (res.code === 1) {
              this.getList()
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    getList() {
      this.loading = true
      // const ossConfig = {
      //   expires: 3600,
      //   process: 'image/auto-orient,1/quality,q_90/format,src'
      // }
      listWebImage({
        // type: 2,
        state: 1
      }).then((res) => {
        if (res.obj) {
          this.list = res.obj.data.map((item) => {
            return Object.assign({}, item, {
              newurl: item.url
              // newurl: this.oss.__main__(item.url, 'readImg', ossConfig)
            })
          })
        }

        this.loading = false
        console.log(this.list)
      })
    },
    submitForm(formName) {
      if (this.contentAddForm.id) {
        if (this.imgurl) {
          const config = Object.assign({}, this.contentAddForm, {
            url: this.imgurl,
            state: 1
          })
          updateWebImage(config).then((res) => {
            if (res.code === 1) {
              this.dialogFormVisible = false
              this.$message.success('新增成功')
              this.imgurl = ''
              this.getList()
            } else {
              this.$message.error(res.msg)
            }
            console.log(res)
          })
        } else {
          this.$message.error('图片上传中，稍后再确认')
        }
      } else {
        console.log(this.contentAddForm.type)

        if (!this.contentAddForm.type) {
          return this.$message.error('请选择图片类型')
        }

        if (this.imgurl) {
          const config = Object.assign({}, this.contentAddForm, {
            url: this.imgurl
          })
          addWebImage(config).then((res) => {
            if (res.code === 1) {
              this.dialogFormVisible = false
              this.$message.success('新增成功')
              this.imgurl = ''
              this.getList()
            } else {
              this.$message.error(res.msg)
            }
            console.log(res)
          })
        } else {
          this.$message.error('图片上传中，稍后再确认')
        }
      }
    },
    beforePicUpload(file) {
      const _this = this
      const isJPG = file.type === 'image/jpeg' || 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        // this.$Mint.Toast(')
        _this.$message.error({
          message: '上传图片只能是jpg或者png格式!'
        })
      }
      if (!isLt2M) {
        // this.$Mint.Toast('')
        _this.$message.error({
          message: '上传图片大小不能超过2MB!'
        })
      }
      // if (this.contentAddForm.type === 2) {
      //   // 轮播图
      //   const isSize = new Promise(function (resolve, reject) {
      //     const width = 540
      //     const height = 340
      //     const _URL = window.URL || window.webkitURL
      //     const img = new Image()
      //     img.onload = function () {
      //       const valid = img.width === width && img.height === height
      //       valid ? resolve() : reject()
      //     }
      //     img.src = _URL.createObjectURL(file)
      //   }).then(
      //     () => {
      //       return file
      //     },
      //     () => {
      //       _this.$message.error({
      //         message: '上传图片长宽需为540*340!'
      //       })
      //       return Promise.reject()
      //     }
      //   )
      //   return isJPG && isLt2M && isSize
      // }
      // if (this.contentAddForm.type === 3) {
      //   // 中图
      //   const isSize = new Promise(function (resolve, reject) {
      //     const width = 1200
      //     const height = 200
      //     const _URL = window.URL || window.webkitURL
      //     const img = new Image()
      //     img.onload = function () {
      //       const valid = img.width === width && img.height === height
      //       valid ? resolve() : reject()
      //     }
      //     img.src = _URL.createObjectURL(file)
      //   }).then(
      //     () => {
      //       return file
      //     },
      //     () => {
      //       _this.$message.error({
      //         message: '上传图片长宽需为1200*200！!'
      //       })
      //       return Promise.reject()
      //     }
      //   )
      //   return isJPG && isLt2M && isSize
      // }
      return isJPG && isLt2M
    },

    handleUploadImg(param) {
      console.log(param)
      this.oss.__main__('activity', 'uploadImg', param).then((res) => {
        if (res.res.status === 200) {
          this.$message.success('上传成功')
          console.log(res.res.requestUrls)
          this.imgurl = res.res.requestUrls[0].split('?uploadId=')[0]
          // this.contentAddForm.image = res.name
          // this.fileList = [
          //   {
          //     name: 'food.jpeg',
          //     url: res.name
          //   }
          // ]
        }
      })
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    }
    // handlePreview(file) {
    //   console.log(file)
    // },
    // delImg(item) {
    //   const arr = []
    //   this.fileList.map((res) => {
    //     if (res.name !== item.name) {
    //       console.log(item.name, res.name)
    //       arr.push(res)
    //     }
    //     console.log(arr, '')
    //     this.fileList = arr
    //   })
    // },
    // visible: function (item) {
    //   this.fileList.map((res) => {
    //     if (res.name === item.name) {
    //       res.showCode = true
    //     }
    //   })
    // },
    // invisible: function () {
    //   this.fileList.map((res) => {
    //     res.showCode = false
    //   })
    // }
  }
}
</script>
<style scoped>
>>> .el-card__body {
  padding: 10px;
}
.delImg {
  width: 20px;
  height: 20px;
}
.delBox {
  position: absolute;
  top: 0;
  right: 0;
  width: 30px;
  height: 30px;
  background: #fdfdff;
  display: flex;
  align-items: center;
  justify-content: center;
}
.uploadImg {
  width: 60px;
  height: 60px;
  display: flex;
  justify-content: center;
}
.btnUpload {
  margin-left: 142px;
  width: 100px;
  height: 100px;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  border: 1px dashed #c0ccda;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
  background: #fdfdff96;
  border-radius: 6px;
  padding: 10px;
}
.listBox {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}
.mycard {
  width: 384px;
  height: 100px;
  text-align: center;
  position: relative;
}
.box {
  width: 100%;
  display: flex;
  align-items: center;
  /* justify-content: center; */
}
.imgList {
  margin-top: 20px;
}
.imgItem {
  position: relative;
  width: 200px;
  height: 200px;
}
.imgItem img {
  width: 200px;
  height: 200px;
}
.delIcon {
  position: absolute;
  width: 20px;
  height: 20px;
  color: #333333;
  line-height: 20px;
  text-align: center;
  background: #f2f2f2;
}
.el-carousel__item h3 {
  color: #475669;
  font-size: 14px;
  opacity: 0.75;
  line-height: 200px;
  margin: 0;
}

.el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n + 1) {
  background-color: #d3dce6;
}
</style>

